<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\api\logic\ai;

use app\api\service\ai\AiAssistantService;
use app\api\service\ai\AiContentService;
use app\api\service\ai\ChatService;
use app\common\enum\YesNoEnum;
use app\common\logic\BaseLogic;
use app\common\model\ai\AiAssistant;
use app\common\model\article\Article;
use app\common\model\article\ArticleCate;
use app\common\model\article\ArticleCollect;
use think\facade\Db;
use think\facade\Log;


/**
 * openai
 */
class AiContentLogic extends BaseLogic
{

    public static function chat($params)
    {
        Db::startTrans();
        try {
            // 预设角色
            $assistant_info = AiAssistantService::getAiAssistantInfo($params['ai_assistant_id'] ?? 0);
            $data           = [
                [
                    'role'    => 'user',
                    'content' => $params['content']
                ]
            ];
            if (!empty($assistant_info)) {
                $arr  = [
                    [
                        'role'    => 'system',
                        'content' => $assistant_info['content']
                    ]
                ];
                $data = array_merge($arr, $data);
            }
            $old_content_arr = AiContentService::getAiContentData(1, 1);
            if (!empty($old_content_arr)) {
                $data = array_merge($old_content_arr, $data);
            }
            $res = (new ChatService())->chat($data);
            Log::record($res);
            AiContentService::saveAiContent($res, $params['content']);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            dd($e->getMessage(), $e->getTrace(), 123);
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }

}